<template>
  <div class="main-content">
    <div class="app-header">
      <div class="go-back" @click="routerOpen('/')">
        <span class="fa fa-angle-left back-icon"></span>
        <span>返回</span>
      </div>
    </div>
    
    <div>
      <zi-note class="notice" v-show="note.show" :type="note.type">
        <span>{{ note.content }}</span>
        <span class="close-notice" @click="closeNotice">X</span>
      </zi-note>
      <zi-row class="form-row">
        <zi-col :span="8" class="form-label _required">
          <zi-tooltip class="label-tooltip" content="生成的图片模板" placement="top">
            <span>当前模板</span>
          </zi-tooltip>
        </zi-col>
        <zi-col :span="16" class="form-input">
          <span>{{ template.name }}</span>
        </zi-col>
      </zi-row>

      <zi-row class="form-row">
        <zi-col :span="8" class="form-label _required">
          <zi-tooltip class="label-tooltip" content="选择需要输出视频的宽高" placement="top">
            <span>视频宽高</span>
          </zi-tooltip>
        </zi-col>
        <zi-col :span="16" class="form-input">
          <div class="flex-left">
            <div class="unit-0" style="width: 200px;">
              <zi-input v-model="resizeWidth" _type="number" placeholde="输入视频宽"></zi-input>
            </div>
            <div class="unit-0" style="width: 40px;line-height: 36px;">
              <span style="">X</span>
            </div>
            <div class="unit">
              <zi-input v-model="resizeHeight" _type="number" placeholde="输入视频高"></zi-input>
            </div>
          </div>
        </zi-col>
      </zi-row>

      <zi-row class="form-row">
        <zi-col :span="8" class="form-label _required">
          <zi-tooltip class="label-tooltip" content="选择需要批量处理的视频素材（可多选）" placement="top">
            <span>选择视频素材</span>
          </zi-tooltip>
        </zi-col>
        <zi-col :span="16" class="form-input">
          <div>
            <zi-button size="small" @click.native="selectVideoAssets">Select Videos</zi-button>
          </div>
          <div class="preview-creative">
            <zi-files :files="fileTree" @file-click="clickFileHandler" style="padding: 15px 0 0 0;"></zi-files>
          </div>
        </zi-col>
      </zi-row>

      <zi-row class="form-row action-btn-row">
        <zi-col :span="8" class="form-label"></zi-col>
        <zi-col :span="16" class="form-input">
          <zi-button type="success" shadow @click.native="submitHandler" :loading="loading">批量转换</zi-button>
          <zi-button @click.native="clearForm" :loading="loading" style="width: 150px;min-width: 150px;">Clear</zi-button>
        </zi-col>
      </zi-row>

      <zi-row class="form-row" v-show="progress.show">
        <zi-col :span="8" class="form-label">
          <span>生成进度</span>
        </zi-col>
        <zi-col :span="10" class="form-input">
          <zi-progress :percentage="progress.percentage" color="#67c23a" :show-text="false"></zi-progress>
        </zi-col>
        <zi-col :span="6" class="progress-tip lh-32">{{ progress.text }}</zi-col>
      </zi-row>
    </div>

    <zi-dialog v-model="dialog1.visible" cancel="取消" done="确认" :beforeDone="confirmDelImage">
      <p>是否删除选中项？</p>
    </zi-dialog>
  </div>
</template>

<script>
  import path from 'path'
  import fs from 'fs'
  import ffmpeg from 'fluent-ffmpeg'
  import ffmpegPath from 'ffmpeg-static'
  import _ from 'lodash'
  import makeDir from 'make-dir'
  import shell from 'any-shell-escape'
  import { exec } from 'child_process'
  import utils from '@/services/utils'
  import remoteTools from '@/services/remoteTools'
  import videoTools from '@/services/videoTools'

  export default {
    name: 'template-2',
    data () {
      return {
        note: {
          show: false,
          type: 'success',
          content: ''
        },
        dialog1: {
          visible: false,
          video: '',
        },
        progress: {
          show: false,
          percentage: 0,
          text: '开始生成'
        },
        template: {
          id: 'template-2',
          name: '视频批量转尺寸',
        },
        videos: [],
        resizeType: '2', // 视频拉伸方式 1、填充（画面可能会变形）; 2、填充背景模糊; 3、裁切
        resizeWidth: '720',
        resizeHeight: '1280',
        loading: false,
      }
    },
    computed: {
      fileTree: function() {
        return this.videos.map( item => {
          return {
            type: 'file',
            name: path.basename(item),
            path: item
          }
        });
      },
    },
    methods: {
      routerOpen (link) {
        location.hash = `#${link}`
      },
      clearForm() {
        this.videos = [];
        this.note = {
          show: false,
          type: 'success',
          content: ''
        };
        this.dialog1 = {
          visible: false,
          video: '',
        };
        this.progress = {
          show: false,
          percentage: 0,
          text: ''
        };
      },
      selectVideoAssets() {
        var paths = remoteTools.chooseVideos();
        // console.log(paths);
        this.videos = _.union(this.videos, paths);
        this.videos = _.uniq(this.videos);
      },
      clickFileHandler(e) {
        // console.log(e);
        // 移除选中项
        this.dialog1 = {
          visible: true,
          video: e.trigger.path,
        };
      },
      confirmDelImage() {
        const v = this.dialog1.video;
        this.videos = _.dropWhile(this.videos, function(o) { return o === v; });
        this.dialog1.visible = false;
        this.$Toast.show('移除成功');
      },
      closeNotice() {
        this.note = {
          show: false,
          type: 'success',
          content: ''
        }
      },
      async submitHandler() {
        var _this = this;
        // 校验
        if(!this.videos.length) {
          this.note = {
            show: true,
            type: 'error',
            content: '请选择视频素材'
          }
          window.scroll(0, 0);
          return;
        }
        if(!this.resizeWidth || !this.resizeHeight) {
          this.note = {
            show: true,
            type: 'error',
            content: '视频宽高不能空'
          }
          window.scroll(0, 0);
          return;
        }
        if(this.resizeWidth <= 0 || this.resizeHeight <= 0) {
          this.note = {
            show: true,
            type: 'error',
            content: '视频宽高无效'
          }
          window.scroll(0, 0);
          return;
        }
        
        this.loading = true;
        // 开始生成
        const obj = {
          videos: this.videos,
          resizeType: this.resizeType,
          resizeWidth: this.resizeWidth,
          resizeHeight: this.resizeHeight,
        };
        console.log(obj);
        this.buildCreatives(obj);
      },
      async buildCreatives(options) {
        const _this = this;
        _this.progress = {
          show: true,
          percentage: 0,
          text: '开始生成'
        };
        let lastOutput = '';
        // 开始处理
        try {
          await makeDir(path.resolve(remoteTools.getDownloadDir(), 'video-batch-maker'));
          // 创建缓存文件夹
          await makeDir(path.resolve(remoteTools.getTmpDir(), 'inmobi'));
          let random = Math.floor(Math.random()*10000+0);
          let outputPath = path.resolve(remoteTools.getDownloadDir(), 'video-batch-maker', `output-${random}.mp4`);
          const videos = options.videos;
          const vnum = videos.length;
          console.log(`共有 ${vnum} 个视频素材`);
          // progress 提示
          _this.progress = {
            show: true,
            percentage: 0,
            text: `开始运行：0/${vnum}`
          };
          // 合成视频
          for (let i = 0; i < vnum; i ++) {
            console.log('开始转换素材 ' + (i + 1) );
            _this.progress = {
              show: true,
              percentage: (i / vnum) * 100,
              text: `开始转换素材：${i + 1}/${vnum}`
            };
            let video = videos[i];
            lastOutput = await videoTools.makeTemplateVideo2(video, options.resizeType, options.resizeWidth, options.resizeHeight);
            console.log('素材 ' + (i + 1) + '合成成功' );
            _this.progress = {
              show: true,
              percentage: 0 / options.num,
              text: `素材合成成功：${i + 1}/${vnum}`
            };
            
          }

          _this.progress = {
            show: true,
            percentage: 100,
            text: `全部处理完成！`
          };
          console.log('全部处理完成！');
          _this.loading = false;
          _this.$Toast.show({
            type: 'success',
            text: '生成成功！文件输出位置："Downloads/video-batch-maker" ',
            duration: 10
          })
          _this.note = {
            show: true,
            type: 'success',
            content: '生成成功！文件输出位置："Downloads/video-batch-maker" '
          }
          // 打开输出文件夹
          remoteTools.showOutputFolder(lastOutput)
          // 清理缓存文件夹
          utils.delDir(path.resolve(remoteTools.getTmpDir(), 'inmobi'))
        } catch (error) {
          this.loading = false;
          console.log('生成出错！');
          console.log(error);
          _this.note = {
            show: true,
            type: 'error',
            content: '生成出错: ' + error.message
          }
        }
      }
    }
  }
</script>

<style>
  @import url('~@/assets/styles/main.css');
</style>